package utils

import (
	"blog/configs"
	"bytes"
	"errors"
	"fmt"
	"github.com/gofiber/fiber/v2/utils"
	"io"
	"io/ioutil"
	"math/rand"
	"mime/multipart"
	"net/http"
	"time"
)

// 获取必应每日一图地址
func GetBingImage() (string, error) {
	resp, err := http.Get("https://api.asilu.com/bg/")
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	var data map[string]interface{}
	if err = configs.Json.Unmarshal(body, &data); err != nil {
		return "", err
	}
	return data["images"].([]interface{})[0].(map[string]interface{})["url"].(string), nil
}

// 上传图片至图床（限5M）
func UploadImageToSMMS(name string, reader io.Reader) (string, error) {
	if name == "" {
		name = utils.UUIDv4()
	}
	// 创建上传文件
	payload := new(bytes.Buffer)
	writer := multipart.NewWriter(payload)
	file, err := writer.CreateFormFile("smfile", name)
	if err != nil {
		return "", err
	}
	if _, err = io.Copy(file, reader); err != nil {
		return "", err
	}
	if err = writer.Close(); err != nil {
		return "", err
	}
	// 构建请求
	req, err := http.NewRequest(http.MethodPost, "https://sm.ms/api/v2/upload", payload)
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	req.Header.Set("Authorization", "VjOiIqgYNKkyVCymdqI6tRTqxcfqjlFQ")
	// 请求
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	// 获取数据
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	var data map[string]interface{}
	if err = configs.Json.Unmarshal(body, &data); err != nil {
		return "", err
	}
	if data["success"].(bool) {
		return data["data"].(map[string]interface{})["url"].(string), nil
	} else if _, ok := data["images"]; ok {
		return data["images"].(string), nil
	} else {
		return "", errors.New(data["message"].(string))
	}
}

// 从本地获取随机名人名言
func GetRandTipFromLocal() string {
	rand.Seed(time.Now().Unix())
	index := rand.Intn(len(configs.Tips))
	return configs.Tips[index]
}

// 从网络中获取一言
func GetRandTipFromWeb() (string, error) {
	resp, err := http.Get("https://v1.hitokoto.cn/")
	if err != nil {
		return "", err
	}
	content, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	var data map[string]interface{}
	if err = configs.Json.Unmarshal(content, &data); err != nil {
		return "", err
	}
	var hitokoto, from string
	if object, ok := data["hitokoto"]; ok {
		hitokoto, ok = object.(string)
	}
	if object, ok := data["from"]; ok {
		from, ok = object.(string)
		if from == "" || from == "原创" {
			from = "佚名"
		}
	}
	return fmt.Sprintf("%s —— %s", hitokoto, from), nil
}
